/**
 * 登录
 */
import { useCurrentUser, useReqBody } from "@sker/runtime";
import { useTransaction, HttpError, encryptPassword } from "@sker/core";
import { CommonCaptcha, SysUser } from "@sker/entities";

import { DependencyContainer } from "tsyringe";
import { z } from "zod";
const input = z.object({
    username: z.string(),
    password: z.string(),
    captcha: z.string(),
    captchaKey: z.string(),
    returnUrl: z.string()
})
export default async (injector: DependencyContainer) => {
    const body = input.parse(useReqBody())
    const sysUser = await useTransaction(async manager => {
        const captcha = await manager.findOne(CommonCaptcha, { where: { hashkey: body.captchaKey } })
        if (!captcha) throw new HttpError(`验证码有误`)

        if (`${captcha.response}`.toLowerCase() !== `${body.captcha}`.toLowerCase()) throw new HttpError(`验证码有误`)
        const sysUser = await manager.findOne(SysUser, {
            where: { username: body.username },
            select: {
                uid: true,
                username: true,
                password: true,
                salt: true,
                status: true,
                welcome_link: true,
                role: true,
                avatar: true,
                login_count: true
            }
        });
        if (!sysUser) throw new HttpError(`账号错误`)
        const pwd = await encryptPassword(body.password, sysUser.salt)
        if (sysUser.password !== pwd) throw new HttpError(`账号或密码错误`)
        const [, setCurrentUser] = useCurrentUser();
        const { uid, username, welcome_link, role, avatar, login_count } = sysUser;
        await manager.update(SysUser, uid, { lastvisit: new Date(), login_count: login_count + 1 })
        setCurrentUser({
            id: uid, uid, username, role
        })
        return { id: uid, uid, username, welcome_link, role, avatar };
    })
    return {
        success: true,
        message: `欢迎您,${sysUser.username}`,
        data: sysUser
    }
}
